// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using MessagePack;
using MessagePack.Formatters;
using Microsoft;

namespace NuGet.VisualStudio.Internal.Contracts
{
    internal sealed class PackageVulnerabilityMetadataContextInfoFormatter : NuGetMessagePackFormatter<PackageVulnerabilityMetadataContextInfo>
    {
        private const string AdvisoryUrlPropertyName = "advisoryurl";
        private const string SeverityPropertyName = "severity";

        internal static readonly IMessagePackFormatter<PackageVulnerabilityMetadataContextInfo?> Instance = new PackageVulnerabilityMetadataContextInfoFormatter();

        private PackageVulnerabilityMetadataContextInfoFormatter()
        {
        }

        protected override PackageVulnerabilityMetadataContextInfo? DeserializeCore(ref MessagePackReader reader, MessagePackSerializerOptions options)
        {
            Uri? advisoryUrl = null;
            int severity = 0;

            int propertyCount = reader.ReadMapHeader();
            for (int propertyIndex = 0; propertyIndex < propertyCount; propertyIndex++)
            {
                switch (reader.ReadString())
                {
                    case AdvisoryUrlPropertyName:
                        advisoryUrl = options.Resolver.GetFormatter<Uri>().Deserialize(ref reader, options);
                        break;
                    case SeverityPropertyName:
                        severity = reader.ReadInt32();
                        break;
                    default:
                        reader.Skip();
                        break;
                }
            }

            Assumes.NotNull(advisoryUrl);

            return new PackageVulnerabilityMetadataContextInfo(advisoryUrl, severity);
        }

        protected override void SerializeCore(ref MessagePackWriter writer, PackageVulnerabilityMetadataContextInfo value, MessagePackSerializerOptions options)
        {
            writer.WriteMapHeader(count: 2);
            writer.Write(AdvisoryUrlPropertyName);
            options.Resolver.GetFormatter<Uri>().Serialize(ref writer, value.AdvisoryUrl, options);
            writer.Write(SeverityPropertyName);
            writer.Write(value.Severity);
        }
    }
}
